//
//  BROrederListViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/9/28.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BROrederListViewController.h"
#import "BROrderListTableViewCell.h"
#import "BROrderDetailViewController.h"
#import "BROderReportViewController.h"
#import "BRPaymentViewController.h"

#define kJXViewHeight 56.f

@interface BROrederListViewController ()<QMUITableViewDelegate,QMUITableViewDataSource>
{
    NSInteger _offset;
}
@property (nonatomic,strong) NSMutableArray *dataArr;


@end

@implementation BROrederListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.dataArr = [NSMutableArray array];
    _offset  = 0;
    
    [self.emptyLYView setImage:UIImageMake(@"error_order")];
    
    [self setUI];
    
    [self addRefreshActionForView:self.tableView];
    [self addLoadMoreActionForView:self.tableView];
    
    self.tableView.mj_footer.hidden = YES;
    
    [self requestList];
}

- (void)handleListRefreshAction {
    _offset = 0;
    [self requestList];
}

- (void)handleListLoadMoreAction {
    // 新接口没有分页参数，不支持加载更多，直接结束刷新
    [self handleEndRefreshForView:self.tableView];
}



- (void)toPayOrder:(BROrderListModel *)dto {
    BRPaymentViewController *payVC = [[BRPaymentViewController alloc] init];
    
    payVC.amount = dto.money;
    payVC.payType = BRPAY_Rent;
    payVC.dto = (BROrderDetailModel *)dto;
    [self.navigationController pushViewController:payVC animated:YES];
}

#pragma mark - Request --
- (void)requestList  {
    [self.tableView ly_startLoading];
    
    // 使用新接口：POST /sw/app/rentbox/order/list.html/V2
    NSDictionary *params = @{@"status": @(0)};
    
    [[BRRequestManager shared] POSTWithFormData:[BRAPI orderListV2] params:params succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        [self.tableView ly_endLoading];
        
        if (self->_offset == 0) {
            [self.dataArr removeAllObjects];
            self.tableView.mj_footer.hidden = NO;
        }
        
        NSInteger oldCount = self.dataArr.count;
        
        // 新接口直接返回data数组，如果没有data字段则直接使用整个响应
        NSArray *orderArray = nil;
        if ([dataDict objectForKey:@"data"] && [[dataDict objectForKey:@"data"] isKindOfClass:[NSArray class]]) {
            orderArray = dataDict[@"data"];
        } else if ([dataDict isKindOfClass:[NSArray class]]) {
            // 如果整个响应就是数组（虽然用户说是data数组，但可能是直接返回数组）
            orderArray = (NSArray *)dataDict;
        } else {
            // 尝试从其他可能的字段获取
            orderArray = @[];
        }
        
        NSArray *arr = [BROrderListModel mj_objectArrayWithKeyValuesArray:orderArray];
        [self.dataArr addObjectsFromArray:arr];
        
        // 判断是否还有更多数据
        if (arr.count < kPageSize || self.dataArr.count == oldCount) {
            self.tableView.mj_footer.hidden = YES;
        }
        
        [self.tableView reloadData];
        [self showBREmptyView];
        [self handleEndRefreshForView:self.tableView];
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [self.tableView ly_endLoading];
        [self showBRErrorView];
        [self handleEndRefreshForView:self.tableView];
    }];
}

#pragma mark - tableView Delegate --

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    return 5;
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BROrderListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BROrderListTableViewCell"];
    BROrderListModel *model = self.dataArr[indexPath.row];
    cell.dto = model;
    
    WS(weakSelf);
    cell.toPayBlock = ^(NSInteger state) {
        [weakSelf toPayOrder:model];
    };
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BROrderListModel *model  = self.dataArr[indexPath.row];
    
    
    BROrderDetailViewController *deVC = [[BROrderDetailViewController alloc] init];
//    if (model.state  == 2) {
//        deVC.status = BROrder_UNPAY;
//    }
    // 传递 orderId (id)，如果 orderId 为0则使用 orderNo (uuid)
    if (model.orderId > 0) {
        deVC.orderNo = [NSString stringWithFormat:@"%ld", (long)model.orderId];
    } else {
    deVC.orderNo = model.orderNo;
    }
    [self.navigationController pushViewController:deVC animated:YES];
    
}

#pragma mark - SET UI --
- (void)setUI {
    
    [self br_createTop:Localized(@"menu_orderRecord")];
    
    self.tableView.estimatedRowHeight = 240;
    self.tableView.rowHeight = 240;
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = UIColor.clearColor;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BROrderListTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"BROrderListTableViewCell"];
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    UIView *head = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 14)];
    self.tableView.tableHeaderView = head;
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
